<script setup>
import { reactive, ref } from 'vue';
import router from '@/router';
import userApi from '@/api/user_api.js';
import loginApi from '@/api/login_api.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Stamp, SwitchButton, Shop, Grid, User, Collection, Document, ShoppingCart,
  Setting, Folder, Star, List, Expand, Fold, PieChart, UserFilled
} from '@element-plus/icons-vue';


const activeIndex = ref('1')

// 存储当前登录用户的信息
const loginAdmin = ref({
  username: "未登录",
});
// 修改信息表单
const editForm = ref({
  username: '',
  email: '',
  phone: '',
  avatar: ''
})
// 修改信息表单规则
const editFormRules = {
  username: [
    {message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    {message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    {message: '请输入手机号', trigger: 'blur' },
    { type: 'string', min: 11, max: 11, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
  ]
}
// 重置密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmNewPassword: ''
})
// 重置密码表单引用
const passwordFormRef = ref(null)
// 重置密码表单规则
const passwordFormRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmNewPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateNewPassword, trigger: 'blur' }
  ]
}
// 验证新密码确认是否一致
function validateNewPassword(rule, value, callback) {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
}
// 获取当前登录用户信息
getLogin();
// 修改信息对话框显示状态
const editDialogVisible = ref(false)

// 重置密码对话框显示状态
const passwordDialogVisible = ref(false)

async function getLogin() {
  let token = localStorage.getItem('token');
  if (!token) {
    await router.push('/login'); // 跳转到登录页
  }

  const res=await loginApi.logininfo();
  loginAdmin.value=res;
  // 初始化编辑表单
  editForm.value.id = res.id;
  editForm.value.username = res.username;
  editForm.value.email = res.email || '';
  editForm.value.avatar = res.avatar || '';
}
// 用户下拉菜单的点击
function handleSelect(key, keyPath){
  if (key == 'logout'){
    // 用户退出
    logout();
  }else if (key == '1-1') {
    // 修改信息
    openEditDialog();
  } else if (key == '1-2') {
    // 重置密码
    openPasswordDialog();
  }
}
// 打开修改信息对话框
function openEditDialog() {
  editDialogVisible.value = true;
}
// 打开重置密码对话框
function openPasswordDialog() {
  passwordDialogVisible.value = true;
  // 重置表单
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmNewPassword: ''
  }
}
// 关闭修改信息对话框
function closeEditDialog() {
  editDialogVisible.value = false;
}

// 关闭重置密码对话框
function closePasswordDialog() {
  passwordDialogVisible.value = false;
}
// 提交修改信息
async function submitEditForm() {
  try {
    await userApi.edit(editForm.value);
    // 更新显示的用户名
    loginAdmin.value.username = editForm.value.username;
    // 更新邮箱
    loginAdmin.value.email = editForm.value.email;
    //更新手机号
    loginAdmin.value.phone = editForm.value.phone;
    // 更新头像
    loginAdmin.value.avatar = editForm.value.avatar;
    closeEditDialog();
  } catch (err) {
    ElMessage.error('信息修改失败');
  }
}
// 提交密码重置
async function submitPasswordForm() {
  try {
    // 先进行表单验证
    const valid = await passwordFormRef.value.validate();
    if (!valid) {
      return; // 验证失败，不继续执行
    }
    const passwordData = {
      username: loginAdmin.value.username,
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword
    };
    const response = await userApi.resetPassword(passwordData);
    if (response) {
      ElMessage.success('密码修改成功');
      closePasswordDialog();
    } else {
      ElMessage.error(response.msg || '密码修改失败');
    }
  } catch (error) {
  }
}
// 左侧菜单动作
function handleMenu(key){
  if (key){
    router.push(key);
  }
}

// 退出
function logout(){
  // 清除Token
  localStorage.removeItem('token')
  // 跳转到登录
  router.push('/login')
}

// 左侧菜单展开折叠
const isCollapse = ref(false);
// 处理头像上传成功
const handleUploadSuccess = (response, file) => {
  console.log("-----------------");
  console.log(response);
  console.log(file);
  editForm.value.avatar = response.data;
}
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            :ellipsis="false"
            background-color="#171a21"
            text-color="#b8b6b4"
            active-text-color="#ffffff"
            @select="handleSelect"
        >
          <el-menu-item index="0" class="logo-item">
            <img src="@/assets/carsystem.png" alt="叮当打车" class="logo" />
            <span class="logo-text">叮当打车</span>
          </el-menu-item>
          <div class="flex-grow" />
          <el-sub-menu index="1" class="user-menu">
            <template #title>
              <el-icon><Stamp /></el-icon>
              <span class="username">{{ loginAdmin ? loginAdmin.username : '未登录' }}</span>
            </template>
            <el-menu-item index="1-1">
              <el-icon><User /></el-icon>
              修改信息
            </el-menu-item>
            <el-menu-item index="1-2">
              <el-icon><Setting /></el-icon>
              重置密码
            </el-menu-item>
            <el-menu-item index="logout">
              <el-icon><SwitchButton /></el-icon>
              退出
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-header>

      <el-container>
        <el-aside width="200px">
          <div class="sidebar-toggle">
            <el-icon @click="isCollapse=!isCollapse" class="toggle-icon">
              <Expand v-if="isCollapse" />
              <Fold v-else />
            </el-icon>
          </div>

          <el-menu
              active-text-color="#1a9fff"
              background-color="#ffffff"
              class="el-menu-vertical-demo"
              default-active="/passenger/map-order"
              text-color="#ffffff"
              :collapse="isCollapse"
              @select="handleMenu"
              :unique-opened="true"
          >
            <!-- 用户功能菜单 -->
            <el-sub-menu index="1">
              <template #title>
                <el-icon><Grid /></el-icon>
                <span>用户界面</span>
              </template>
              <el-menu-item index="/passenger/UserMap">
                <el-icon><Location /></el-icon>
                <span>地图打车</span>
              </el-menu-item>
              <el-menu-item index="/passenger/place-order">
                <el-icon><Tickets /></el-icon>
                <span>发送订单</span>
              </el-menu-item>
              <el-menu-item index="/passenger/driver-application">
                <el-icon><Stamp /></el-icon>
                <span>注册司机</span>
              </el-menu-item>
            </el-sub-menu>
            <!-- 司机功能菜单 -->
            <el-sub-menu index="2">
              <template #title>
                <el-icon><Grid /></el-icon>
                <span>司机界面</span>
              </template>
            </el-sub-menu>

            <el-sub-menu index="3">
              <template #title>
                <el-icon><Grid /></el-icon>
                <span>管理员界面</span>
              </template>
              <el-menu-item index="/driver-approval">
                <el-icon><User /></el-icon>
                <span>司机审批</span>
              </el-menu-item>
              <el-menu-item index="/user">
                <el-icon><User /></el-icon>
                <span>用户列表</span>
              </el-menu-item>
              <el-menu-item index="/driver">
              <el-icon><UserFilled /></el-icon>
              <span>司机列表</span>
              </el-menu-item>
              <el-menu-item index="/admin">
                <el-icon><Management /></el-icon>
                <span>管理员列表</span>
              </el-menu-item>
              <el-menu-item index="/car">
                <el-icon><Van /></el-icon>
                <span>车辆管理</span>
              </el-menu-item>
              <el-menu-item index="/order">
                <el-icon><Document /></el-icon>
                <span>订单管理</span>
              </el-menu-item>
              <el-menu-item index="/evaluation">
                <el-icon><ChatLineRound /></el-icon>
                <span>评价管理</span>
              </el-menu-item>

            </el-sub-menu>

            <!-- 管理员菜单 - 仅管理员可见 -->
            <template v-if="loginAdmin && loginAdmin.role === '管理员'">
              <el-sub-menu index="4">
                <template #title>
                  <el-icon><Setting /></el-icon>
                  <span>管理系统</span>
                </template>
                <el-menu-item index="/user">
                  <el-icon><User /></el-icon>
                  <span>用户管理</span>
                </el-menu-item>
                <el-menu-item index="/game">
                  <el-icon><Shop /></el-icon>
                  <span>游戏管理</span>
                </el-menu-item>
                <el-menu-item index="/game_category">
                  <el-icon><Folder /></el-icon>
                  <span>游戏分类</span>
                </el-menu-item>
                <el-menu-item index="/game_review">
                  <el-icon><Star /></el-icon>
                  <span>游戏评价</span>
                </el-menu-item>
                <el-menu-item index="/game_sales">
                  <el-icon><Histogram /></el-icon>
                  <span>销售统计</span>
                </el-menu-item>
                <el-menu-item index="/shopping_cart">
                  <el-icon><ShoppingCart /></el-icon>
                  <span>购物车记录</span>
                </el-menu-item>
                <el-menu-item index="/user_game">
                  <el-icon><Collection /></el-icon>
                  <span>用户拥有游戏</span>
                </el-menu-item>
                <el-menu-item index="/order">
                  <el-icon><Document /></el-icon>
                  <span>订单管理</span>
                </el-menu-item>
                <el-menu-item index="/order_item">
                  <el-icon><List /></el-icon>
                  <span>订单项管理</span>
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-menu>
        </el-aside>


        <!-- 主内容区域 -->
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>

  <!-- 修改信息对话框 -->
  <el-dialog v-model="editDialogVisible" title="修改信息" width="500px" class="custom-dialog">
    <el-form :model="editForm" :rules="editFormRules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="editForm.username" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="editForm.phone" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img v-if="editForm.avatar" :src="editForm.avatar" style="width: 100px; height: 100px; object-fit: cover;" />
          <img v-else src="@/assets/upload.png" style="width: 100px; height: 100px;" />
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeEditDialog" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="submitEditForm" class="confirm-button">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 重置密码对话框 -->
  <el-dialog v-model="passwordDialogVisible" title="重置密码" width="500px" class="custom-dialog">
    <el-form :model="passwordForm" :rules="passwordFormRules" label-width="100px" ref="passwordFormRef">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmNewPassword">
        <el-input v-model="passwordForm.confirmNewPassword" type="password" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closePasswordDialog" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="submitPasswordForm" class="confirm-button">确定</el-button>
      </span>
    </template>
  </el-dialog>


</template>

<style scoped>
.common-layout,
.el-container {
  height: 100vh;
}

/* 顶部导航栏 - 高德主色调优化 */
.el-header {
  padding: 0;
  background-color: #0e88eb; /* 高德地图主蓝色 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

.el-menu.el-menu--horizontal {
  border: none;
  background-color: #0e88eb;
}

.el-menu-item.logo-item {
  background-color: #0e88eb !important;
  padding-left: 20px !important;
}

.logo {
  height: 32px;
  margin-right: 12px;
  vertical-align: middle;
}

.logo-text {
  color: white;
  font-size: 19px;
  font-weight: 600;
  vertical-align: middle;
}

.flex-grow {
  flex-grow: 1;
}

.user-menu :deep(.el-sub-menu__title) {
  background-color: #0e88eb !important;
  color: white !important;
  height: 60px;
  padding-right: 20px !important;
  transition: background-color 0.3s;
}

.user-menu :deep(.el-sub-menu__title:hover) {
  background-color: #0a76d9 !important; /* 深一点的蓝色 */
}

.username {
  margin-left: 6px;
}

/* 侧边栏样式 - 高德地图辅助色系 */
.el-aside {
  background-color: #f0f7ff; /* 高德浅蓝背景 */
  box-shadow: 2px 0 10px rgba(14, 136, 235, 0.1);
  transition: width 0.3s ease;
  position: relative;
  z-index: 999;
  height: calc(100vh - 60px);
}

.sidebar-toggle {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 50px;
  padding: 0 20px;
  cursor: pointer;
  border-bottom: 1px solid #e1edff;
  background-color: white;
}

.toggle-icon {
  font-size: 20px;
  color: #0e88eb;
  transition: transform 0.3s;
}

.toggle-icon:hover {
  transform: scale(1.1);
}

.el-menu-vertical-demo {
  border: none !important;
  height: calc(100% - 50px);
  background-color: white;
}

.el-menu-vertical-demo :deep(.el-sub-menu__title) {
  height: 50px;
  font-size: 15px;
  color: #333;
  background-color: transparent;
  border-bottom: 1px solid #f0f7ff;
  padding-left: 25px !important;
  transition: all 0.2s;
}

.el-menu-vertical-demo :deep(.el-sub-menu__title:hover) {
  background-color: #e6f0ff !important; /* 悬停浅蓝色 */
  color: #0e88eb !important;
}

.el-menu-vertical-demo :deep(.el-menu-item) {
  height: 45px;
  font-size: 14px;
  color: #666;
  border-bottom: 1px solid #f7f9fc;
  padding-left: 45px !important;
  transition: all 0.2s;
}

.el-menu-vertical-demo :deep(.el-menu-item:hover) {
  background-color: #e6f0ff !important;
  color: #0e88eb !important;
}

.el-menu-vertical-demo :deep(.el-menu-item.is-active) {
  color: #0e88eb !important;
  background-color: #e6f0ff !important;
  font-weight: 500;
  border-left: 3px solid #0e88eb;
}

/* 主内容区域 - 地图风格背景 */
.el-main {
  background-color: #f7f9fc; /* 地图浅色背景 */
  padding: 20px;
  overflow-y: auto;
}

/* 对话框样式 - 高德风格弹窗 */
.custom-dialog :deep(.el-dialog__header) {
  background-color: #0e88eb;
  color: white;
  padding: 15px 20px;
}

.custom-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 500;
}

.custom-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  transition: all 0.2s;
}

.custom-dialog :deep(.el-dialog__headerbtn .el-dialog__close:hover) {
  background-color: rgba(255, 255, 255, 0.2);
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 20px;
  background-color: white;
}

.custom-dialog :deep(.el-dialog__footer) {
  padding: 15px 20px;
  background-color: #f7f9fc;
  border-top: 1px solid #eee;
}

/* 按钮样式 - 高德风格按钮 */
.confirm-button {
  background-color: #0e88eb !important;
  border-color: #0e88eb !important;
  color: white !important;
  transition: all 0.2s !important;
}

.confirm-button:hover {
  background-color: #0a76d9 !important;
  border-color: #0a76d9 !important;
}

.cancel-button {
  border-color: #0e88eb !important;
  color: #0e88eb !important;
  background-color: transparent !important;
  transition: all 0.2s !important;
}

.cancel-button:hover {
  background-color: #f0f7ff !important;
}

/* 表单元素样式优化 */
:deep(.el-input__wrapper) {
  border-radius: 4px;
  transition: all 0.2s;
}

:deep(.el-input__wrapper:focus-within) {
  box-shadow: 0 0 0 2px rgba(14, 136, 235, 0.2) !important;
  border-color: #0e88eb !important;
}

:deep(.el-upload) {
  transition: all 0.2s;
}

:deep(.el-upload:hover) {
  filter: brightness(1.05);
}

/* 动画效果增强 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease-in-out;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计优化 */
@media (max-width: 768px) {
  .logo-text {
    display: none;
  }

  .el-menu-item.logo-item {
    padding-right: 20px !important;
  }

  .el-aside {
    width: 64px !important;
  }

  .el-menu-vertical-demo :deep(.el-sub-menu__title span),
  .el-menu-vertical-demo :deep(.el-menu-item span) {
    display: none;
  }

  .el-menu-vertical-demo :deep(.el-menu-item) {
    padding-left: 20px !important;
  }
}
</style>
